import React, { FormEvent, useState, ChangeEvent } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import './style.scss';
import { login } from '@/api/user';

interface LocationState {
    from?: {
        pathname: string;
    };
}

const Login: React.FC = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const [username, setUsername] = useState<string>('');
    const [password, setPassword] = useState<string>('');

    const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault();

        try {
            const result = await login({ username, password });
            // 保存 token
            localStorage.setItem('token', result.token);

            // 获取之前要访问的页面路径，如果没有则跳转到首页
            const from = (location.state as LocationState)?.from?.pathname || '/home';
            navigate(from, { replace: true });
        } catch (error) {
            // 错误已在响应拦截器中处理
            console.error('登录失败:', error);
        }
    };

    const handleInputChange = (e: ChangeEvent<HTMLInputElement>, setter: (value: string) => void) => {
        setter(e.target.value);
    };

    return (
        <div className="login-container">
            <div className="login-box">
                <h2>登录</h2>
                <form className="login-form" onSubmit={handleSubmit}>
                    <div className="form-item">
                        <input
                            type="text"
                            placeholder="用户名"
                            value={username}
                            onChange={(e) => handleInputChange(e, setUsername)}
                        />
                    </div>
                    <div className="form-item">
                        <input
                            type="password"
                            placeholder="密码"
                            value={password}
                            onChange={(e) => handleInputChange(e, setPassword)}
                        />
                    </div>
                    <button type="submit" className="login-button">
                        登录
                    </button>
                </form>
            </div>
        </div>
    );
};

export default Login; 